import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:wan_android_flutter/pages/hot_key/hot_key_vm.dart';
import 'package:wan_android_flutter/route/RouteUtils.dart';

import '../../common_ui/web/webview_page.dart';
import '../../common_ui/web/webview_widget.dart';
import '../../repository/datas/common_website_data.dart';
import '../../repository/datas/search_hot_keys_data.dart';
import '../../search/search_page.dart';

class HotKeyPage extends StatefulWidget {
  const HotKeyPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HotKeyPageState();
  }
}

//常用网站item回调
typedef WebsiteClick = Function(String name, String link);

class _HotKeyPageState extends State<HotKeyPage> {
  HotKeyViewModel viewModel = HotKeyViewModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    viewModel.initData();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        body: SafeArea(
            child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                height: 45.h,
                decoration: BoxDecoration(
                    border: Border(
                        top: BorderSide(width: 0.5.r, color: Colors.grey),
                        bottom: BorderSide(width: 0.5.r, color: Colors.grey))),
                padding: EdgeInsets.only(left: 20.w, right: 20.w),
                child: Row(
                  children: [
                    Text(
                      "搜索热词",
                      style: TextStyle(fontSize: 14.sp, color: Colors.black),
                    ),
                    const Expanded(child: SizedBox()),
                    GestureDetector(
                      onTap: () {
                        RouteUtils.push(context, const SearchPage());
                      },
                      child: Image.asset(
                        "assets/images/icon_search.png",
                        width: 30.r,
                        height: 30.r,
                      ),
                    )
                  ],
                ),
              ),

              ///搜索热词列表
              Consumer<HotKeyViewModel>(builder: (context, vm, child) {
                return _gridView(false, keyList: vm.keyList, itemTap: (value) {
                  //进入搜索页面
                  RouteUtils.push(
                      context,
                      SearchPage(
                        keyword: value,
                      ));
                });
              }),

              Container(
                  height: 45.h,
                  alignment: Alignment.centerLeft,
                  decoration: BoxDecoration(
                      border: Border(
                          top: BorderSide(width: 0.5.r, color: Colors.grey),
                          bottom:
                              BorderSide(width: 0.5.r, color: Colors.grey))),
                  margin: EdgeInsets.only(top: 20.h),
                  padding: EdgeInsets.only(left: 20.w, right: 20.w),
                  child: Text(
                    "常用网站",
                    style: TextStyle(fontSize: 14.sp, color: Colors.black),
                  )),

              ///常用网站列表
              Consumer<HotKeyViewModel>(builder: (context, vm, child) {
                return _gridView(true, websiteList: vm.websiteList,
                    websiteClick: (name, link) {
                  //跳转到网页
                  RouteUtils.push(
                      context,
                      WebViewPage(
                        loadResource: link,
                        webViewType: WebViewType.URL,
                        showTitle: true,
                        title: name,
                      ));
                });
              }),
            ],
          ),
        )),
      ),
    );
  }

  Widget _gridView(bool? isWebsite,
      {String? link,
      List<CommonWebsiteData>? websiteList,
      List<SearchHotKeysData>? keyList,
      ValueChanged<String>? itemTap,
      WebsiteClick? websiteClick}) {
    return Container(
      margin: EdgeInsets.only(top: 20.r),
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
            //主轴的间隔
            mainAxisSpacing: 8.r,
            //最大横轴范围
            maxCrossAxisExtent: 120.w,
            //宽高比
            childAspectRatio: 3,
            //横轴间隔
            crossAxisSpacing: 8.r),
        itemBuilder: (context, index) {
          if (isWebsite == true) {
            return _item(
                name: websiteList?[index].name,
                link: websiteList?[index].link,
                websiteClick: websiteClick);
          } else {
            return _item(name: keyList?[index].name, itemTap: itemTap);
          }
        },
        itemCount:
            isWebsite == true ? websiteList?.length ?? 0 : keyList?.length ?? 0,
      ),
    );
  }

  Widget _item(
      {String? name,
      ValueChanged<String>? itemTap,
      String? link,
      WebsiteClick? websiteClick}) {
    return GestureDetector(
      onTap: () {
        if (link != null) {
          websiteClick?.call(name ?? "", link);
          //?.call(link);
        } else {
          itemTap?.call(name ?? "");
        }
      },
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
            border: Border.all(color: Colors.grey, width: 0.5.r),
            borderRadius: BorderRadius.all(Radius.circular(10.r))),
        child: Text(name ?? ""),
      ),
    );
  }
}
